<?php

require_once  'error.php';

class common {

    static function sn() {
        return sprintf('%04x%04x-%04x%04x-%04x%04x-%04x%04x',
                // 32 bits for "time_low"
                mt_rand(0, 0xffff), mt_rand(0, 0xffff),
                // 16 bits for "time_mid"
                mt_rand(0, 0xffff),
                // 16 bits for "time_hi_and_version",
                // four most significant bits holds version number 4
                mt_rand(0, 0x0fff) | 0x4000,
                // 16 bits, 8 bits for "clk_seq_hi_res",
                // 8 bits for "clk_seq_low",
                // two most significant bits holds zero and one for variant DCE1.1
                mt_rand(0, 0x3fff) | 0x8000,
                // 48 bits for "node"
                mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        );
    }

    static function trim($s) {
        //return $s;
        $message = trim($s);
        $message = str_replace("\r\n", " ", $message);
        $message = str_replace("\r", " ", $message);
        $message = str_replace("\n", " ", $message);
        return $message;
        // return trim($message, '\r\n\t\x0B');
    }

    static function curlget($url, $params) {
        $start_time = explode(" ", microtime());
        $ch = curl_init();

        //$querys = http_build_query($params);
        $querys = $params;
        $url = $url . "?" . $querys;

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);

        $content = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);


        $end_time = explode(" ", microtime());
        $cost = intval(($end_time[0] + $end_time[1] - $start_time[1] - $start_time[0]) * 1000);
        if ($code != 200) {
            hilog::debug("curlget: [$url] [cost:$cost] [querydata:$querys], [httpcode:$code] [content:$content]");
            return null;
        }

        hilog::debug("curlget: [$url] [cost:$cost] [querydata:$querys], [httpcode:$code] [content:$content]");

        return $content;
    }

    static function curlpost($url, $postdata) {
        $start_time = explode(" ", microtime());
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'X-ptype: like me'
        ));

        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        $content = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        $end_time = explode(" ", microtime());

        $cost = intval(($end_time[0] + $end_time[1] - $start_time[1] - $start_time[0]) * 1000);

        if ($code != 200) {
            hilog::error("curlpost: [$url][cost: $cost], [postdata:$postdata], [httpcode:$code] [content:$content]");
            return null;
        }

        hilog::debug("curlpost: [$url][cost: $cost], [postdata:$postdata], [httpcode:$code] [content:$content]");
        return $content;
    }

    static function curlpostjson($url, $params) {
        $postdata = json_encode($params);
        $content = common::curlpost($url, $postdata);
        if (!$content) {
            set_last_error(E_INTERNAL, "crash!");
            return false;
        }

        $json = json_decode($content, true);

        if (!$json) {
            set_last_error(E_INTERNAL, "crash, json_decode failed!");
            return false;
        }

        if ($json['status'] != 0) {
            if (isset($json['message'])) {
                set_last_error(E_INTERNAL, $json['message']);
            } else {
                set_last_error(E_INTERNAL, 'status = ' . $json['status']);
            }
            return false;
        }

        return $json;
    }

    static function check_json_keys($jsdata, $fields, &$what) {
        $data = array();
        foreach ($fields as $key => $type) {
            if (!array_key_exists($key, $jsdata)) {
                if (preg_match("/^opt/", $type)) {
                    $data[$key] = null;
                    continue;
                } else {
                    $what = $key . " miss ";
                    return false;
                }
            }

            $val = $jsdata[$key];
            $match = false;
            do {
                if (preg_match('/string$/', $type)) {
                    if (!is_string($val))
                        break;
                } else if (preg_match('/int$/', $type)) {
                    if (!is_int($val))
                        break;
                } else if (preg_match('/date$/', $type)) {
                    if (!common::is_date($val))
                        break;
                } else if (preg_match('/datetime$/', $type)) {
                    if (!common::is_datetime($val))
                        break;
                } else if (preg_match('/time$/', $type)) {
                    if (!common::is_time($val))
                        break;
                } else if (preg_match('/array$/', $type)) {
                    if (!is_array($val))
                        break;
                } else if (preg_match('/intarray$/', $type)) {
                    if (!is_array($val))
                        break;
                    foreach ($val as $sv) {
                        if (!is_int($sv))
                            break;
                    }
                } else if (preg_match('/stringarray$/', $type)) {
                    if (!is_array($val))
                        break;
                    foreach ($val as $sv) {
                        if (!is_string($sv) || empty($sv))
                            break;
                    }
                }
                $match = true;
            } while (0);

            if (!$match) {
                $what = "$key must be $type ";
                return null;
            }
            $data[$key] = $val;
        }
        return $data;
    }

    static function is_date($date) {
        if (preg_match("/^(\d{4})-(\d{2})-(\d{2})$/", $date, $matches)) {
            if (checkdate($matches[2], $matches[3], $matches[1])) {
                return true;
            }
        }
        return false;
    }

    static function is_datetime($dateTime) {
        if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $dateTime, $matches)) {
            //debuginfo("is_datetime preg matches:".json_encode($matches));
            if (checkdate($matches[2], $matches[3], $matches[1])) {
                return true;
            }
        }
        return false;
    }

    static function is_time($time) {
        if (preg_match("/^([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $time, $matches)) {
            return true;
        }
        return false;
    }

    static function sql_row($selectlist, $row) {
        $ret = [];
        foreach ($selectlist as $key => $type) {
            if (array_key_exists($key, $row)) {
                if ($type == 'int') {
                    $ret[$key] = intval($row[$key]);
                } else {
                    $ret[$key] = $row[$key];
                }
            }
        }
        return $ret;
    }

    static function convertUTF8($str) {
        if (empty($str))
            return '';
        return iconv("utf8", "utf8", $str);
    }

}
